package com.simpd.activity;


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Iterator;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import android.app.ActionBar;
import android.app.Activity;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import cn.pedant.SweetAlert.SweetAlertDialog;

import com.example.simpd.R;
import com.simpd.http_helper.CustomHttpClient;

public class ExampleActivity extends Activity {
	Button btnGetJson;
	TextView textResult;
	
	EditText inputString; 
	Button btnSubmit; 
	TextView textOriginal; 
	TextView textResult2;
	
	
	SweetAlertDialog loadingDialog;
	
	public static final String SAMPLE_URL 	= "http://sppd.gorontaloprov.go.id/simpd/rencanaPD/cetakSppd/ttd/id/12805";
	public static final String DEFAULT_UNIP = "196206062012011001";
	
	final String SIMPD_DIR_PATH 	 = Environment.getExternalStorageDirectory()+"/simpd/";
	final String CSS_DIR_PATH 		 = SIMPD_DIR_PATH+"css/";
	final String JS_DIR_PATH 		 = SIMPD_DIR_PATH+"js/";
	final String JSIGNATURE_DIR_PATH = JS_DIR_PATH+"jsignature/";
	
	final String JQUERY_JS 		 	= "jquery.js"; 
	final String JQUERY_MOBILE_CSS 	= "jquery.mobile-1.4.5.min.css";
	final String JQUERY_MOBILE_JS  	= "jquery.mobile-1.4.5.min.js";
	final String JSIGNATURE_JS		= "jSignature.min.js";
	
	
	private String respond = null; 
	private String errorMessage = "";
	
	private JSONObject jsonObject;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		ActionBar actionBar = getActionBar(); 
		actionBar.hide();
		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.example);
		
		btnGetJson = (Button) findViewById(R.id.example_button_get_json); 
		btnSubmit  = (Button) findViewById(R.id.example_button_submit); 
		textResult = (TextView) findViewById(R.id.example_text_result1); 
		
		textOriginal = (TextView) findViewById(R.id.example_text_original); 
		textResult2	 = (TextView) findViewById(R.id.example_text_result2); 
		
		textResult.setText("sebelum request"); 
		textOriginal.setText(""); 
		textResult2.setText(""); 
		
		btnGetJson.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				String url = "http://192.168.0.125/nusaraya/index.php/simpd_controller/test_json";
				Thread thread = new Thread(new LoadJsonThread(url));
				thread.start();
			}
		});
		
	} 
	
	private void testDownload(View v){
		String url = SAMPLE_URL;
		ArrayList<NameValuePair> getParameters = new ArrayList<NameValuePair>(); 
		getParameters.add(new BasicNameValuePair("unip", DEFAULT_UNIP));
		
		Thread thread = new Thread(new MyLoadHtmlThread(url, getParameters));
		thread.start();
		
		
	}
	
	private void loadHtmlUsingThread(String url, ArrayList<NameValuePair> parameters){
		String paramUrl= "?";
		
		for (Iterator<NameValuePair> iterator = parameters.iterator(); iterator.hasNext();) {
			NameValuePair param = (NameValuePair) iterator.next();
			paramUrl+=param.getName()+"="+param.getValue();
			if(iterator.hasNext()){
				paramUrl+="&";
			}
			
		}
		
		try {
			Log.d("[get-request]", "get request with url : \n"+(url+paramUrl));
			respond = CustomHttpClient.executeHttpGet(url+paramUrl);
			respond = respond.toString();
			Log.d("[get-respond]", "respond result : "+respond);
			
			
		} catch (Exception e) {
			errorMessage = e.getMessage();
			e.printStackTrace();
		}finally{
			ExampleActivity.this.runOnUiThread(new Runnable() {
				
				@Override
				public void run() {
					SweetAlertDialog alert;
					
					String dir = Environment.getExternalStorageDirectory()+"/simpd/sample/";
					boolean createDir = new File(dir).mkdir();
					Log.d("[create-dir]", "create directory sample successfully ? "+createDir);
					File file = new File(dir, "test.html");
					String result = respond.toString(); 
					result = result.replace("/simpd/css/jquery.mobile-1.4.5.min.css", "../css/jquery.mobile-1.4.5.min.css");
					result = result.replace("/simpd/js/jsignature/jquery.js", "../js/jsignature/jquery.js");
					result = result.replace("/simpd/js/jsignature/jSignature.min.js", "../js/jsignature/jSignature.min.js");
					result = result.replace("/simpd/js/jquery.mobile-1.4.5.min.js", "../js/jquery.mobile-1.4.5.min.js");
					
					writeData(file, result);
					respond = result;
					Log.d("[result-string]", result);
					if(errorMessage != null){
						alert = new SweetAlertDialog(ExampleActivity.this, SweetAlertDialog.SUCCESS_TYPE); 
						alert.setTitleText("Good..!!");
						alert.setContentText("respon : \n"+respond);
						
					}else{
						alert = new SweetAlertDialog(ExampleActivity.this, SweetAlertDialog.ERROR_TYPE);
						alert.setTitleText("Oops..!!");
						alert.setContentText("terjadi kesalahan karena : \n"+errorMessage);
					}
					alert.show();
				}
			});

		}
	}
	
	private void writeData(File file, String text){
		SweetAlertDialog alert = null;
		FileOutputStream fileOutputStream = null;
		try {
			file.createNewFile();
			if(file.exists()){
				fileOutputStream = new FileOutputStream(file);
				fileOutputStream.write(text.getBytes());
			}
		} catch (IOException e) {
			alert = new SweetAlertDialog(ExampleActivity.this, SweetAlertDialog.ERROR_TYPE);
			alert.setTitleText("Oops..!!");
			alert.setContentText("terjadi kesalahan karena : \n"+e.getMessage());
			alert.show();
			e.printStackTrace();
		}finally{
			if(fileOutputStream != null){
				try {
					fileOutputStream.close();
				} catch (IOException e) {
					alert = new SweetAlertDialog(ExampleActivity.this, SweetAlertDialog.ERROR_TYPE); 
					alert.setTitleText("Oops..!!"); 
					alert.setContentText("Terjadi kesalahan : "+e.getMessage());
					alert.show();
					e.printStackTrace();
				}
			}
		}
	}
	
	/**
	 * digunakan untuk meng-copy file css dan js untuk 
	 * dokumen offline. 
	 */
	private void putAssetFiles(){
		ArrayList<String> targetDirPaths = new ArrayList<String>(); 
		targetDirPaths.add(SIMPD_DIR_PATH);
		targetDirPaths.add(CSS_DIR_PATH);
		targetDirPaths.add(JS_DIR_PATH); 
		targetDirPaths.add(JSIGNATURE_DIR_PATH); 
		
		boolean isTargetCreated = false; 
		
		for (String dirPath : targetDirPaths) {
			isTargetCreated = new File(dirPath).mkdir();
			Log.d("[create-dir]", "create dir "+dirPath+" successfully ? : "+isTargetCreated);
		}
		
		AssetManager assetManager 	= ExampleActivity.this.getAssets(); 
		String[] assetNames 		= null; 
		
		try {
			assetNames = assetManager.list("");
			String assetNamesToString	= null;
			
			for (int i = 0; i < assetNames.length; i++) {
				assetNamesToString+= " "+assetNames[i]+", ";
			}
			Log.d("assets-files", "asset files : "+assetNamesToString);
			
			File file = null;
			InputStream in 		= null; 
			OutputStream out 	= null; 
			
			for (String assetFile : assetNames) {
				try {
					
					if(assetFile.equalsIgnoreCase(JQUERY_JS) || assetFile.equalsIgnoreCase(JSIGNATURE_JS)){
						file = new File(JSIGNATURE_DIR_PATH, assetFile);
					}else if(assetFile.equalsIgnoreCase(JQUERY_MOBILE_JS)){
						file = new File(JS_DIR_PATH, assetFile);
					}else if(assetFile.equalsIgnoreCase(JQUERY_MOBILE_CSS)){
						file = new File(CSS_DIR_PATH, assetFile);
					}
					
										
					if(file != null && !file.exists()){
						in 	= assetManager.open(assetFile);
						out = new FileOutputStream(file);
						copyFile(in, out);
						in.close();
						in 	= null;
						out.flush(); 
						out.close();
						out = null;
						Log.d("[copying-data]", "successfully copying data..!");
					}
				} catch (Exception e) {
					SweetAlertDialog alert = new SweetAlertDialog(ExampleActivity.this, SweetAlertDialog.ERROR_TYPE);
					alert.setTitleText("Oops..!!"); 
					alert.setContentText("Terjadi kesalahan : "+e.toString());
					alert.show();
					e.printStackTrace();
				}
				
			}
			
			
			
		} catch (IOException e) {
			SweetAlertDialog alert = new SweetAlertDialog(ExampleActivity.this, SweetAlertDialog.ERROR_TYPE); 
			alert.setTitleText("Oops..!!"); 
			alert.setContentText("Terjadi kesalahan : "+e.getMessage());
			alert.show();
			e.printStackTrace();
		}
		
		
		
	}
	
	private void copyFile(InputStream in, OutputStream out){
		byte[] buffer = new byte[1024];
		int read ; 
		try {
			while((read=in.read(buffer)) != -1){
				out.write(buffer, 0, read);
			}
		} catch (IOException e) {
			Log.e("[error - copyFile]", "copying file error cause : "+e.getMessage());
		}
	}
	
	private class MyLoadHtmlThread implements Runnable{
		private ArrayList<NameValuePair> parameters = new ArrayList<NameValuePair>();
		private String url ;
		
		public MyLoadHtmlThread(String url, ArrayList<NameValuePair> parameters) {
			this.url 		= url; 
			this.parameters = parameters;
		}
		
		@Override
		public void run() {
			loadHtmlUsingThread(url, parameters);
		}
		
	}
	
	private void loadJsonUsingThread(String url){
		try {
			Log.d("[load json]", "url : "+url);
			respond = CustomHttpClient.executeHttpGet(url);
			respond = respond.toString();
			Log.d("[json result]", respond);
			
			jsonObject = new JSONObject(respond);
			JSONObject data = jsonObject.getJSONObject("data");
			data.put("keterangan", "sampel keterangan");
			jsonObject.remove("data"); 
			jsonObject.put("data", data);
			
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			ExampleActivity.this.runOnUiThread(new Runnable() {
				
				@Override
				public void run() {
					if(loadingDialog != null){
						loadingDialog.dismiss(); 
					}
					
					textResult.setText("hasil : "+respond);
					textResult2.setText("hasil 2: \n"+jsonObject.toString());
				}
			});
		}
	}
	
	private class LoadJsonThread implements Runnable{
		private String url; 
		public LoadJsonThread(String url) {
			this.url = url;
		}
		@Override
		public void run() {
			ExampleActivity.this.runOnUiThread(new Runnable() {
				
				@Override
				public void run() {
					loadingDialog = new SweetAlertDialog(ExampleActivity.this, SweetAlertDialog.PROGRESS_TYPE);
					loadingDialog.setTitleText("waiting request...");
					loadingDialog.setContentText("loading..."); 
					loadingDialog.show();
				}
				
			});
			
			loadJsonUsingThread(this.url);
			
		}
		
	}
	
}
